var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
// var jwt = require("express-jwt");
var { secretKey, unless, algorithms } = require("./utils/token");
var session = require("express-session");

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var filesRouter = require('./routes/files');

const art = require('express-art-template');

var app = express();
app.engine('html',art);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
// app.set('view engine', 'jade');


app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());

app.use(express.static(path.join(__dirname, 'public')));
// app.use(jwt({secret:secretKey,algorithms}).unless(unless));
app.use(
  session({
      secret: "bankbank",
      resave: false, // 强制保存session，默认为true，即使它没有变化，建议false
      saveUninitialized: true, // 强制将未初始化的session存储（当新建一个sesison，但未设定属性和值时处于未初始化状态）
  })
);
app.use(function (req, res, next) {
  // next();
  // return;
  console.log("path",req.url);
  if (req.session.user) {
      if(req.url == "/"){
        res.render('upfile.html');
        return;
      }
      next();
  } else {
      if (
          unless.path.filter((item) => {
            
              if (item instanceof RegExp) {
                
                  if (item.test(req.url)) {
                    
                      return true;
                  }
              } else {
                  if (item == req.url) {
                      return true;
                  }
              }
          }).length > 0
      ) {
          next();
      } else {
          res.send({ status: 401, msg: "请先登录" });
      }
  }
});
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/files', filesRouter);

// catch 404 and forward to error handler
// app.use(function(req, res, next) {
//   res.header("Access-Control-Allow-Origin", "*");
//   res.header("Access-Control-Allow-Methods", "*");
//   res.header("Access-Control-Allow-Headers", "*");
//   res.header("Access-Control-Allow-Credentials", true); 
//   next();
// });
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};
  if (err.status === 401) {
      res.send({ status: 401, msg: "权限不足" });
      return;
  }

  console.log("err",err.status);
//   res.sendStatus(404);
  // render the error page
//   res.status(err.status || 500);
//   res.status(500);
  res.send({ status: err.status, msg: err.message });
});


module.exports = app;
